import pandas as pd
from flask import (Blueprint, request, session)
from flaskr import Utils
from flaskr.server.FilterDataServer import *
import json
from flaskr.server.SheetsServer import *
bp = Blueprint('merge',__name__, url_prefix='/merge')

#列的合并
@bp.route('',methods = ['POST'])
def merge():
    data_name = request.json.get('data_name')
    sheet_name = request.json.get('sheet_name')

    column_names = request.json.get('column_names')
    new_column_name = request.json.get('new_column_name')
    symbol = request.json.get('symbol')

    sheet = get_sheet(sheet_name)
    df = get_dataframe(sheet_name)
    if sheet is not None and df is not None:
        df_concat = column_merge(df, column_names, new_column_name, symbol)

        if has_pkl(sheet_name):
            setPkl(df_concat, sheet['md5'])
            df_concat = df_concat.head(200)

        sheet['table'] = Utils.dataFrameToHtml(df_concat)
        sheet['json'] = Utils.dataFrameToJson(df_concat)
        sheet['columns'] = Utils.getColumns(df_concat)
        sheet['types'] = Utils.getTypes(df_concat)

        set_sheet(sheet_name, sheet)

        filter_data_server = FilterDataServer(session)
        filter_data_server.remove_filter_container(sheet_name)

        return {
            'msg': '合并成功',
            'code': 200,
            'data': sheet
        }

    # df = Utils.jsonToDataFrame(json_)
     #获取一个合并后的数据

    return{
        'msg': '合并失败',
        'code': 500,
        'data': None,
    }




#数据的合并 第一个参数是DataFrame, 第二个参数是要合并列的列名数组， 第三个参数是合并后的新列的名字， 第四个参数是合并数据的连接符
def column_merge(df, column_names, new_column_name, symbol):
    list_ = [] #存储合并数据的列表

    for column_name in column_names:
        for i in range(df[column_name].count()):
            if(len(list_) <= i):

                if(df[column_name][i] is not str):
                    list_.append( str(df[column_name][i]))

                else:
                    list_.append(df[column_name][i])
            else:

                if(list_[i] is not str):
                    list_[i] += symbol + str(df[column_name][i])

    columns = getColumns(df) #获取数据的所有列

    removeArray(columns, column_names) #删除要合并的列

    df_filter = df.loc[:, columns] #过滤要合并的列

    dict_ = {}

    dict_[new_column_name] = list_

    df_new = pd.DataFrame(dict_) #将合并后的数据存放了变量当中

    df_concat = pd.concat([df_filter, df_new], axis=1) #合并数据

    return df_concat

#返回一个DataFrame的所有列的数组
def getColumns(df):
    columns = []
    for column in df.columns:
        columns.append(column)
    
    return columns

#删除数组中的元素   第一个参数是数组   第二个参数是数组要删除的元素
def removeArray(arr, data):

    if (type(data) is list):
        for d in data:
            arr.remove(d)

    else:
        arr.remove(data)